<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="评价计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择评价计划"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="督导类型" prop="supervisionType">
        <el-select
          v-model="queryParams.supervisionType"
          placeholder="请选择督导类型"
          clearable
          class="!w-240px"
        >
          <el-option label="现场督导" value="onsite" />
          <el-option label="远程督导" value="remote" />
          <el-option label="专项督导" value="special" />
          <el-option label="常规督导" value="regular" />
        </el-select>
      </el-form-item>
      <el-form-item label="督导状态" prop="supervisionStatus">
        <el-select
          v-model="queryParams.supervisionStatus"
          placeholder="请选择督导状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待督导" :value="0" />
          <el-option label="督导中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="需整改" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="督导日期" prop="supervisionDate">
        <el-date-picker
          v-model="queryParams.supervisionDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:supervision:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="info"
          plain
          @click="openReportGenerate"
          v-hasPermi="['eval:supervision:report']"
        >
          <Icon icon="ep:document" class="mr-5px" /> 生成报告
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:supervision:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 督导统计卡片 -->
  <el-row :gutter="20" class="mb-4">
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-blue-600">{{ statistics.totalCount || 0 }}</div>
            <div class="text-gray-500">总督导数</div>
          </div>
          <Icon icon="ep:view" class="text-4xl text-blue-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-green-600">{{ statistics.completedCount || 0 }}</div>
            <div class="text-gray-500">已完成</div>
          </div>
          <Icon icon="ep:check" class="text-4xl text-green-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-orange-600">{{ statistics.inProgressCount || 0 }}</div>
            <div class="text-gray-500">督导中</div>
          </div>
          <Icon icon="ep:loading" class="text-4xl text-orange-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-purple-600">{{ statistics.averageScore || 0 }}</div>
            <div class="text-gray-500">平均得分</div>
          </div>
          <Icon icon="ep:trophy" class="text-4xl text-purple-600" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评价计划" align="center" prop="planName" width="200" />
      <el-table-column label="督导员" align="center" prop="supervisorName" width="120" />
      <el-table-column label="督导日期" align="center" prop="supervisionDate" width="120" />
      <el-table-column label="督导类型" align="center" prop="supervisionType" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.EVAL_SUPERVISION_TYPE" :value="scope.row.supervisionType" />
        </template>
      </el-table-column>
      <el-table-column label="督导内容" align="center" prop="supervisionContent" width="200" />
      <el-table-column label="督导结果" align="center" prop="supervisionResult" width="200" />
      <el-table-column label="督导得分" align="center" prop="supervisionScore" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.supervisionScore" :type="getScoreTagType(scope.row.supervisionScore)">
            {{ scope.row.supervisionScore }}分
          </el-tag>
          <span v-else class="text-gray-400">未评分</span>
        </template>
      </el-table-column>
      <el-table-column label="督导状态" align="center" prop="supervisionStatus" width="100">
        <template #default="scope">
          <el-tag :type="getSupervisionStatusTagType(scope.row.supervisionStatus)">
            {{ getSupervisionStatusText(scope.row.supervisionStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:supervision:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:supervision:update']"
            v-if="scope.row.supervisionStatus < 2"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="submit" v-if="scope.row.supervisionStatus === 0">
                  提交
                </el-dropdown-item>
                <el-dropdown-item command="audit" v-if="scope.row.supervisionStatus === 1">
                  审核
                </el-dropdown-item>
                <el-dropdown-item command="template">
                  督导模板
                </el-dropdown-item>
                <el-dropdown-item command="delete">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SupervisionForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <SupervisionDetail ref="detailRef" />
  
  <!-- 审核弹窗 -->
  <SupervisionAudit ref="auditRef" @success="getList" />
  
  <!-- 督导模板弹窗 -->
  <SupervisionTemplate ref="templateRef" />
  
  <!-- 报告生成弹窗 -->
  <ReportGenerate ref="reportGenerateRef" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { 
  EvalSupervisionRecordVO, 
  EvalSupervisionRecordPageReqVO, 
  getSupervisionRecordPage, 
  deleteSupervisionRecord, 
  exportSupervisionRecord,
  getSupervisionStatistics,
  submitSupervisionRecord,
  auditSupervisionRecord,
  generateSupervisionReport
} from '@/api/eval/supervision'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import SupervisionForm from './SupervisionForm.vue'
import SupervisionDetail from './SupervisionDetail.vue'
import SupervisionAudit from './SupervisionAudit.vue'
import SupervisionTemplate from './SupervisionTemplate.vue'
import ReportGenerate from './ReportGenerate.vue'

/** 督导检查 列表 */
defineOptions({ name: 'EvalSupervision' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalSupervisionRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const statistics = ref<any>({}) // 统计数据
const planList = ref<EvalPlanVO[]>([]) // 计划列表
const queryParams = reactive<EvalSupervisionRecordPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  planId: undefined,
  supervisionType: undefined,
  supervisionStatus: undefined,
  supervisionDate: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getSupervisionRecordPage(queryParams)
    list.value = data.list
    total.value = data.total
    
    // 加载统计数据
    await loadStatistics()
  } finally {
    loading.value = false
  }
}

/** 加载统计数据 */
const loadStatistics = async () => {
  try {
    statistics.value = await getSupervisionStatistics()
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 审核操作 */
const auditRef = ref()
const openAudit = (id: number) => {
  auditRef.value.open(id)
}

/** 督导模板操作 */
const templateRef = ref()
const openTemplate = (supervisionType: string) => {
  templateRef.value.open(supervisionType)
}

/** 报告生成操作 */
const reportGenerateRef = ref()
const openReportGenerate = () => {
  reportGenerateRef.value.open()
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalSupervisionRecordVO) => {
  switch (command) {
    case 'submit':
      await handleSubmit(row.id!)
      break
    case 'audit':
      openAudit(row.id!)
      break
    case 'template':
      openTemplate(row.supervisionType)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 提交督导 */
const handleSubmit = async (id: number) => {
  try {
    await submitSupervisionRecord(id)
    message.success('提交成功')
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteSupervisionRecord(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportSupervisionRecord(queryParams)
    download.excel(data, '督导检查.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取督导状态标签类型 */
const getSupervisionStatusTagType = (status: number) => {
  const typeMap = { 0: 'warning', 1: 'primary', 2: 'success', 3: 'danger' }
  return typeMap[status] || ''
}

/** 获取督导状态文本 */
const getSupervisionStatusText = (status: number) => {
  const textMap = { 0: '待督导', 1: '督导中', 2: '已完成', 3: '需整改' }
  return textMap[status] || '未知'
}

/** 获取得分标签类型 */
const getScoreTagType = (score: number) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'primary'
  if (score >= 70) return 'warning'
  return 'danger'
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取进行中的计划
    planList.value = await getPlanListByStatus(4) // 进行中
  } catch (error) {
    console.error('加载计划列表失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  loadPlanList()
  getList()
})
</script>
